package org.nbict.iot.protocol.util;

/**
 * Created by songseven on 18/6/10.
 */
public class BinaryUtil {
    private static int IntegerMask = 0xffffffff;


    /**
     *
     * @param number
     * @param offset
     * @return
     */
    public static int setBit(int number, int offset) {
        checkOffset(offset);
        return number | (1 << (offset - 1));
    }


    /**
     *
     * @param number
     * @param offset
     * @return
     */
    public static int unsetBit(int number, int offset) {
        checkOffset(offset);
        int unsetMask = IntegerMask ^ (1 << (offset - 1));
        return number & unsetMask;
    }


    /**
     *
     * @param number
     * @param offset
     * @return
     */
    public static boolean checkBit(int number, int offset) {
        checkOffset(offset);
        return (number & (1 << (offset - 1))) != 0;
    }

    /**
     *
     * @param offset
     */
    private static void checkOffset(int offset) {
        if (offset > 32 || offset < 1) {
            // throw exception
        }
    }

    public static void main(String[] args) {
        int a = 15; //0x 00 00 00 0f
        int b = unsetBit(a, 3); //00000000 00000000 00000000 00001011
        // System.out.println(b);
        System.out.println(checkBit(b, 1));
        System.out.println(checkBit(b, 2));
        System.out.println(checkBit(b, 3));
        System.out.println(checkBit(b, 4));
    }
}
